| Total Complexity | 15 |
| Total Lines | 71 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | import { URL } from 'url' |
||
| 3 | export default class URLString { |
||
| 4 | constructor () { |
||
| 5 | 26 | this.url = null |
|
| 6 | 26 | this.path = {} |
|
| 7 | 26 | this.searchParams = {} |
|
| 8 | } |
||
| 9 | |||
| 10 | setUrl (url) { |
||
| 11 | 26 | if (!url || url.constructor !== String) { |
|
| 12 | 1 | throw new Error('url isnt a valid string') |
|
| 13 | } |
||
| 14 | 25 | this.url = new URL(url).href |
|
| 15 | } |
||
| 16 | |||
| 17 | setSearchParams (searchParams) { |
||
| 18 | 23 | if (!searchParams) { |
|
| 19 | 14 | return |
|
| 20 | } |
||
| 21 | 9 | if (searchParams.constructor !== Object) { |
|
| 22 | 1 | throw new Error('searchParams isnt a valid object') |
|
| 23 | } |
||
| 24 | 8 | this.searchParams = searchParams |
|
| 25 | } |
||
| 26 | |||
| 27 | setPath (path) { |
||
| 28 | 24 | if (!path) { |
|
| 29 | 2 | return |
|
| 30 | } |
||
| 31 | 22 | if (path.constructor !== Object) { |
|
| 32 | 1 | throw new Error('path isnt a valid object') |
|
| 33 | } |
||
| 34 | 21 | this.path = path |
|
| 35 | } |
||
| 36 | |||
| 37 | urlReducer (accumulator, [key, value]) { |
||
| 38 | 34 | if (!value) { |
|
| 39 | 2 | return accumulator + '/' + key |
|
| 40 | } |
||
| 41 | |||
| 42 | 32 | return accumulator + '/' + key + '/' + value |
|
| 43 | } |
||
| 44 | |||
| 45 | toString () { |
||
| 46 | 22 | const completeUrl = new URL(Object.entries(this.path).reduce(this.urlReducer, this.url)) |
|
| 47 | 22 | Object.entries(this.searchParams).forEach(([searchParam, searchValue]) => { |
|
| 48 | 9 | if (searchValue) { |
|
| 49 | 7 | completeUrl.searchParams.append(searchParam, searchValue) |
|
| 50 | } |
||
| 51 | }) |
||
| 52 | |||
| 53 | 22 | return completeUrl.href |
|
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Generate an url from the url, path and search params |
||
| 58 | * |
||
| 59 | * @param {string} url |
||
| 60 | * @param {object} path |
||
| 61 | * @param {object} searchParams |
||
| 62 | * |
||
| 63 | * @return {string} |
||
| 64 | */ |
||
| 65 | static create ({ url, path, searchParams }) { |
||
| 66 | 26 | const newUrl = new URLString() |
|
| 67 | 26 | newUrl.setUrl(url) |
|
| 68 | 24 | newUrl.setPath(path) |
|
| 69 | 23 | newUrl.setSearchParams(searchParams) |
|
| 70 | |||
| 71 | 22 | return newUrl.toString() |
|
| 72 | } |
||
| 73 | } |
||
| 74 |